package run.siyuan.rabbitmq.retry.message.consumer;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import run.siyuan.common.constant.rabbitmq.Constants;
import run.siyuan.rabbitmq.retry.message.service.CommonMessageDelayService;

import java.io.IOException;

/**
 * 正常消费
 */
@Slf4j
@Component
public class ServiceConsumer extends CommonMessageDelayService {

    @RabbitListener(queues = Constants.Queue.RABBITMQ_SERVICE_QUEUE, ackMode = "MANUAL", concurrency = "1")
    private void consumer(Message message, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) throws IOException {
        try {
            byte[] body = message.getBody();
            String msg = new String(body);
            log.info("【正常队列】【" + System.currentTimeMillis() + "】收到死信队列消息：" + msg);
            JSONObject json = JSONUtil.parseObj(msg);
            if (json.getInt("id") < 0) {
                throw new Exception("id 小于 0");
            }
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.info("消费异常：{}", e.getMessage());
            channel.basicNack(deliveryTag, false, false);
            sendDelayMessage(message, e);
        }
    }

}
